package com.spider.admin.controller.advice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.spider.admin.conf.ResultMessage;
import com.spider.admin.http.entity.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

@Slf4j
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 此方法返回 true 则执行下面的 beforeBodyWrite 方法,反之则不执行
     *
     * @param returnType    the return type
     * @param converterType the selected converter type
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ResponseEntity responseEntity = new ResponseEntity();
        if (body instanceof ResponseEntity) {
            responseEntity = (ResponseEntity) body;
        } else {

            responseEntity = new ResponseEntity();
            responseEntity.setCode(ResultMessage.SUCCESS.getCode());
            responseEntity.setMessage(ResultMessage.SUCCESS.getMessage());
            responseEntity.setData(body);
            // 这里需要进行特殊处理，因为 String 在转换的时候报错
            if (body instanceof String) {
                try {
                    return objectMapper.writeValueAsString(responseEntity);
                } catch (Exception e) {

                    log.error(e.getMessage());
                }
            }
        }
//        log.info("{}方法调用{}服务", request.getMethod(), request.getURI());
        return responseEntity;
    }
}

